package org.bbl.utils;

import java.util.*;
import java.util.regex.Pattern;

/**
 * @author biniamg
 * @since 10/1/12
 */
public class StringUtils {

    private static final Pattern PATTERN = Pattern.compile("'");

    public static String listToString(final Collection<?> list, final String separator) {
        return listToString(list, separator, "");
    }

    public static String listToString(final Collection<?> list, final String separator, String sufix) {
        if (list.isEmpty()) {
            return "";
        }
        if (list.size() == 1) {
            return list.iterator().next().toString();
        }
        final StringBuilder builder = new StringBuilder();
        for (Iterator<?> iterator = list.iterator(); iterator.hasNext(); ) {
            final Object element = iterator.next();
            if (element != null && element.toString() != null) {
                builder.append(element);
                builder.append(sufix);
                if (separator != null && iterator.hasNext()) {
                    builder.append(separator);
                }
            }
        }
        return builder.toString();
    }

    public static String mapToSql(String tableName, Map<String, Object> message) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("INSERT INTO ").append(tableName);
        stringBuilder.append(" (").append(listToString(message.keySet(), ",")).append(" )");
        stringBuilder.append(" VALUES (");
        List<String> values = new ArrayList<String>();
        for (Object o : message.values()) {
            values.add("'" + escapeQuotes(o.toString()) + "'");
        }
        stringBuilder.append(listToString(values, ","));
        stringBuilder.append(")");
        // System.out.println("s.toCharArray() = " + s.toCharArray());
        return stringBuilder.toString();
    }

    public static String escapeQuotes(final String value) {
        return PATTERN.matcher(value).replaceAll("''");
    }

}
